//
//  Formula.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 27.03.25.
//

import Foundation
class Formula {
    private var symbols: Array<Symbol> = Array()
    private var elements: Array<Element> = Array()
    

    func calc(formulaContent: String) -> String {
        parseSymbolAndElement(content: formulaContent.trimmingCharacters(in: .whitespaces))
        let i = 0
        while(i < symbols.count) {
            let symbol = symbols[i]
            calcPriority(symbol: symbol, index: i)
            symbols.remove(at: i)
        }
        return elements[elements.count - 1].parse()
    }
    
    private func calcPriority(symbol: Symbol, index: Int) {
        let element1 = elements[index]
        let element2 = elements[index + 1]
        let result = Symbol.calc(s1:element1.parse(),s2:element2.parse(), op:symbol.op)
        elements[index] = Element(str:result)
        elements.remove(at: index + 1)
    }
    
    private func parseSymbolAndElement(content: String) {
        symbols.removeAll()
        elements.removeAll()
        elements.append(Element())
        var last = -1
        for index in content.indices {
            let i = content.distance(from: content.startIndex, to: index)
            let c = content[index]
            if (Symbol.isOperator(char:c) && content.last == c) {
                break
            }
            // 如果是连续的符号，第二个符号给数字 1,2
            if (Symbol.isOperator(char:c) && (1 != i - last)) {
                if (1 == i - last) {
                    // 连续的第二个符号，是数字
                    let element = elements[elements.count - 1]
                    element.add(s:String(c))
                } else {
                    symbols.append(Symbol(op:String(c)))
                    let element = Element()
                    elements.append(element)
                }
                last = i
            }else {
                let element = elements[elements.count - 1]
                element.add(s:String(c))
            }
        }
    }
}
